﻿using System.ComponentModel.Composition;
using System.Linq;
using System.Xml.Linq;
using Microsoft.VisualStudio.SharePoint;
using WSPHelper.VSExtensions.Core;

namespace WSPHelper.VSExtensions.Extensions
{

    [Export(typeof(ISharePointProjectItemTypeExtension))]
    [SharePointProjectItemType("Microsoft.VisualStudio.SharePoint.Module")]
    public class SpModuleProjectItemExtension : ISharePointProjectItemTypeExtension
    {
        public void Initialize(ISharePointProjectItemType projectItemType)
        {
            projectItemType.ProjectItemMenuItemsRequested += (sender, args) =>
            {
                args.ViewMenuItems.Add("Alphabetise file references").Click += 
                    (sender2, args2) => AlphabetiseModule(projectItemType.ProjectService, (ISharePointProjectItem)args2.Owner);

                args.ViewMenuItems.Add("Sanitise file references").Click +=
                    (sender2, args2) => SanitiseModule(projectItemType.ProjectService, (ISharePointProjectItem)args2.Owner);

            };
        }


        static void AlphabetiseModule(ISharePointProjectService svc, ISharePointProjectItem moduleProjectItem)
        {
            svc.Log("Alphabetising file references in SharePoint module " + moduleProjectItem.Name);

            // TODO Is elements.xml always the default file???
            ISharePointProjectItemFile elementsFile = moduleProjectItem.DefaultFile;
            string elementsFilePath = elementsFile.FullPath;

            svc.LogVar("path", elementsFilePath);

            var elementsXmlDoc = XDocument.Load(elementsFilePath);
            
            foreach(var moduleNode in elementsXmlDoc.Root.Elements())
            {
                // TODO: error handling
                var newFileNodes = moduleNode.Elements()
                    .OrderBy(e => e.Attribute("Path").Value)
                    .ThenBy(e => e.Attribute("Url").Value)
                    .ToArray();
                
                moduleNode.RemoveAll();
                moduleNode.Add(newFileNodes);
            }

            svc.Log("Saving");
            elementsXmlDoc.Save(elementsFilePath);
        }


        static void SanitiseModule(ISharePointProjectService svc, ISharePointProjectItem moduleProjectItem)
        {
            svc.Log("Sanitising file references in SharePoint module " + moduleProjectItem.Name);

            // TODO Is elements.xml always the default file???
            ISharePointProjectItemFile elementsFile = moduleProjectItem.DefaultFile;
            string elementsFilePath = elementsFile.FullPath;

            svc.LogVar("path", elementsFilePath);

            var elementsXmlDoc = XDocument.Load(elementsFilePath);

            foreach(var fileNode in elementsXmlDoc.Root.Elements().SelectMany(e => e.Elements()))
            {
                // TODO: Don't naively overwrite
                fileNode.SetAttributeValue("IgnoreIfAlreadyExists", "True");
                fileNode.SetAttributeValue("Type", "GhostableInLibrary");
                
            }

            svc.Log("Saving");
            elementsXmlDoc.Save(elementsFilePath);
        }
    }

}



